import ElementBaseInfo from "./base/ElementBaseInfo";
// import ElementOtherConfig from "./other/ElementOtherConfig.vue";
import ElementTask from "./task/ElementTask";
// import ElementMultiInstance from "./multi-instance/ElementMultiInstance.vue";
// import FlowCondition from "./flow-condition/FlowCondition.vue";
// import SignalAndMassage from "./signal-message/SignalAndMessage.vue";
// import ElementListeners from "./listeners/ElementListeners.vue";
// import ElementProperties from "./properties/ElementProperties.vue";
// // import ElementForm from './form/ElementForm.vue'
// import UserTaskListeners from "./listeners/UserTaskListeners.vue";
import ElementCustomConfig from "./custom-config/ElementCustomConfig";
import PanelContext from "./PanelContext";

import { Collapse } from "antd";
import Icon from "@/components/Icon";
import { useEffect, useState } from "react";
import { cloneDeep } from "lodash-es";
const { Panel } = Collapse;

const PanelPropsDefault = {
	bpmnModeler: {},
	prefix: "camunda",
	width: 480,
	idEditDisabled: false
};

// let bpmnElement: any = null;
export default function MyPropertiesPanel(props: any) {
	// fix React18 "defaultProps" problem
	props = Object.assign({}, { ...PanelPropsDefault, ...props });

	const [activeTab, setActiveTab] = useState("base");
	const [elementId, setElementId] = useState("");
	const [elementType, setElementType] = useState("");
	const [elementBusinessObject, setElementBusinessObject] = useState<any>({}); // 元素 businessObject 镜像，提供给需要做判断的组件使用
	const [conditionFormVisible, setConditionFormVisible] = useState(false); // 流转条件设置
	const [formVisible, setFormVisible] = useState(false); // 表单配置
	// const isLoad = useRef(false);

	// provide('prefix', props.prefix)
	// provide('width', props.width)
	const bpmnInstances = () => (window as any)?.bpmnInstances;

	const getActiveElement = () => {
		// 初始第一个选中元素 bpmn:Process
		initFormOnChanged(null);
		props.bpmnModeler.on("import.done", () => {
			initFormOnChanged(null);
		});
		// 监听选择事件，修改当前激活的元素以及表单
		props.bpmnModeler.on("selection.changed", ({ newSelection }) => {
			initFormOnChanged(newSelection[0] || null);
		});
		props.bpmnModeler.on("element.changed", ({ element }) => {
			// 保证 修改 "默认流转路径" 类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
			if (element && element.id === elementId) {
				initFormOnChanged(element);
			}
		});
	};
	// 初始化数据
	const initFormOnChanged = element => {
		let activatedElement = element;
		if (!activatedElement) {
			activatedElement =
				bpmnInstances().elementRegistry.find(el => el.type === "bpmn:Process") ??
				bpmnInstances().elementRegistry.find(el => el.type === "bpmn:Collaboration");
		}
		if (!activatedElement) return;
		bpmnInstances().bpmnElement = activatedElement;
		// bpmnElement.value = activatedElement;
		// bpmnElement = activatedElement;
		// elementId.value = activatedElement.id;
		setElementId(activatedElement.id);
		// elementType.value = activatedElement.type.split(":")[1] || "";
		setElementType(activatedElement.type.split(":")[1] || "");
		// elementBusinessObject.value = JSON.parse(JSON.stringify(activatedElement.businessObject));
		setElementBusinessObject(cloneDeep(activatedElement.businessObject));
		// conditionFormVisible.value = !!(
		// 	elementType === "SequenceFlow" &&
		// 	activatedElement.source &&
		// 	activatedElement.source.type.indexOf("StartEvent") === -1
		// );
		setConditionFormVisible(
			elementType === "SequenceFlow" && activatedElement.source && activatedElement.source.type.indexOf("StartEvent") === -1
		);
		// formVisible.value = elementType === "UserTask" || elementType === "StartEvent";
		setFormVisible(elementType === "UserTask" || elementType === "StartEvent");
	};

	const initModels = () => {
		// 避免加载时 流程图 并未加载完成
		if (!props.bpmnModeler) {
			console.log("缺少props.bpmnModeler");
			return;
		}
		const w = window as any;
		w.bpmnInstances = {
			modeler: props.bpmnModeler,
			modeling: props.bpmnModeler.get("modeling"),
			moddle: props.bpmnModeler.get("moddle"),
			eventBus: props.bpmnModeler.get("eventBus"),
			bpmnFactory: props.bpmnModeler.get("bpmnFactory"),
			elementFactory: props.bpmnModeler.get("elementFactory"),
			elementRegistry: props.bpmnModeler.get("elementRegistry"),
			replace: props.bpmnModeler.get("replace"),
			selection: props.bpmnModeler.get("selection")
		};
		getActiveElement();
	};

	/** Effect */

	// 监听 props.bpmnModeler 然后 initModels
	useEffect(() => {
		initModels();
	}, [props.bpmnModeler]);

	useEffect(() => {
		setActiveTab("base");
	}, [elementId]);

	useEffect(() => {
		return () => {
			const w = window as any;
			w.bpmnInstances = null;
		};
	}, []);

	return (
		<div className="process-panel__container" style={{ width: `${props.width}px`, maxHeight: "700px" }}>
			<Collapse activeKey={activeTab} onChange={(val: string[]) => setActiveTab(val)}>
				<Panel
					key="base"
					header={
						<>
							<Icon icon="ep:info-filled" />
							常规
						</>
					}
				>
					<ElementBaseInfo
						idEditDisabled={props.idEditDisabled}
						businessObject={elementBusinessObject}
						type={elementType}
						model={props.model}
					/>
				</Panel>
				{elementType === "Process" && (
					<Panel
						name="condition"
						key="message"
						header={
							<>
								<Icon icon="ep:comment" />
								消息与信号
							</>
						}
					>
						2{/* <signal-and-massage /> */}
					</Panel>
				)}
				{conditionFormVisible && (
					<Panel
						name="condition"
						key="condition"
						header={
							<>
								<Icon icon="ep:promotion" />
								流转条件
							</>
						}
					>
						3{/* <flow-condition :business-object="elementBusinessObject" :type="elementType" /> */}
					</Panel>
				)}
				{formVisible && (
					<Panel
						name="condition"
						key="form"
						header={
							<>
								<Icon icon="ep:list" />
								表单
							</>
						}
					>
						4{/* <element-form :id="elementId" :type="elementType" /> */}
					</Panel>
				)}
				{elementType.indexOf("Task") !== -1 && (
					<Panel
						name="task"
						key="task"
						header={
							<>
								<Icon icon="ep:checked" />
								任务（审批人）
							</>
						}
					>
						<ElementTask id={elementId} type={elementType} />
					</Panel>
				)}
				{elementType.indexOf("Task") !== -1 && (
					<Panel
						name="multiInstance"
						key="multiInstance"
						header={
							<>
								<Icon icon="ep:help-filled" />
								多实例（会签配置）
							</>
						}
					>
						6{/* <element-multi-instance :business-object="elementBusinessObject" :type="elementType" /> */}
					</Panel>
				)}
				<Panel
					name="listeners"
					key="listeners"
					header={
						<>
							<Icon icon="ep:bell-filled" />
							执行监听器
						</>
					}
				>
					7{/* <element-listeners :id="elementId" :type="elementType" /> */}
				</Panel>
				{elementType === "UserTask" && (
					<Panel
						name="taskListeners"
						key="taskListeners"
						header={
							<>
								<Icon icon="ep:bell-filled" />
								任务监听器
							</>
						}
					>
						8{/* <user-task-listeners :id="elementId" :type="elementType" /> */}
					</Panel>
				)}
				<Panel
					name="extensions"
					key="extensions"
					header={
						<>
							<Icon icon="ep:circle-plus-filled" />
							扩展属性
						</>
					}
				>
					9{/* <element-properties :id="elementId" :type="elementType" /> */}
				</Panel>
				<Panel
					name="other"
					key="other"
					header={
						<>
							<Icon icon="ep:promotion" />
							其他
						</>
					}
				>
					10
					{/* <element-other-config :id="elementId" /> */}
				</Panel>
				{elementType.indexOf("Task") !== -1 && (
					<Panel
						name="customConfig"
						key="customConfig"
						header={
							<>
								<Icon icon="ep:circle-plus-filled" />
								自定义配置
							</>
						}
					>
						<PanelContext.Provider value={{ prefix: props.prefix, width: props.width }}>
							<ElementCustomConfig id={elementId} type={elementType} />
						</PanelContext.Provider>
					</Panel>
				)}
			</Collapse>
		</div>
	);
}
